<template>
  <div>
    <el-form label-width="120px" :model="form" ref="form" :rules="rulesForm">
      <el-form-item :label="$t('订单编号')">
        <div style="line-height: 32px">
          {{ rows.loanRecordId }}
        </div>
      </el-form-item>
      <el-form-item :label="$t('合同金额')">
        <div style="line-height: 32px">
          {{ rows.passAmount }}
        </div>
      </el-form-item>
      <el-form-item :label="$t('待还罚息')">
        <div style="line-height: 32px">
          {{ rows.residueOverdueFine }}
        </div>
      </el-form-item>
      <el-form-item :label="$t('优惠券')" prop="couponId">
        <el-select v-model="form.couponId" @change="couponChange">
          <el-option v-for="item in couponSelectList" :key="item.id" :label="item.name"
                     :value="item.id">
            <span style="float: left">{{ item.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.deductibleAmount }}</span>
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('剩余应还金额')">
        <div style="line-height: 32px">
          {{ form.notRefundAmount }}
        </div>
      </el-form-item>
      <el-form-item :label="$t('还款银行')" prop="receiverBank">
        <el-select v-model="form.receiverBank">
          <el-option v-for="item in backList" :key="item.bankAccount" :label="item.alias"
                     :value="item.alias"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('实际还款时间')" prop="actualRefundTimestamp">
        <el-date-picker
            value-format="yyyy-MM-dd HH:mm:ss"
            v-model="form.actualRefundTimestamp"
            type="datetime"
            :picker-options="pickerOptions"
            :placeholder="$t('选择日期时间')">
        </el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('还款金额')" prop="actualRefundAmount">
        <el-input v-model="form.actualRefundAmount" oninput="value = value.replace(/[^\d.]/g, '')"></el-input>
      </el-form-item>
      <el-form-item :label="$t('交易流水')" prop="transferNumber">
        <el-input v-model="form.transferNumber"></el-input>
      </el-form-item>
      <el-form-item :label="$t('备注')" prop="description">
        <el-input type="textarea" :rows="3" v-model="form.description"></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {doRefund} from '@/api/finance'
import {fetchRepaymentBank,} from '@/api/pay'
import {fetchAvailableCoupons} from '@/api/finance'

export default {
  name: "offlineForm",
  props: ['rows'],
  data() {
    return {
      form: {},
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now();
        },
      },
      backList: [],
      rulesForm: {
        receiverBank: [
          {required: true, message: this.$t('请选择还款银行'),},
        ],
        actualRefundAmount: [
          {required: true, message: this.$t('请输入还款金额'),},
        ],
        couponId: [
          {required: true, message: this.$t('请选择'), trigger: 'change'},
        ],
        actualRefundTimestamp: [
          {required: true, message: this.$t('请选择还款时间'),},
        ]
      },
      couponSelectList: []
    }
  },
  watch: {
    rows: {//深度监听
      immediate: true,
      handler(val) {
        this.form.notRefundAmount = val.notRefundAmount
        this.getCollectionBack(val)
        this.getCouponSelect(val)
      },
    }
  },
  methods: {
    submitForm() {
      return new Promise((resolve) => {
        this.$refs.form.validate(async v => {
          if (v) {
            this.$confirm(this.$t("为避免造成损失，请确认是否进行该操作") + '?', this.$t("提示"), {
              type: "warning",
            }).then(async () => {
              this.$emit('loading', true)
              const res = await doRefund(
                  {
                    ...this.form,
                    loanRecordId: this.rows.loanRecordId,
                    couponId: [10001, 10002].indexOf(this.rows.couponId) === -1 ? this.form.couponId : null,
                  }
              )
              if (res.code === 1) {
                resolve(res.code)
                this.$emit('loading', false)
                this.$message.success(this.$t('操作成功'))
              } else {
                this.$emit('loading', false)
              }
            }).catch(() => {
            });
          }
        })
      })
    },

    // 获取收款银行列表
    async getCollectionBack(row) {
      fetchRepaymentBank(row).then(res => {
        this.backList = res.data
        if (this.backList && this.backList.length) {
          this.$set(this.form, 'receiverBank', this.backList[0].alias)
        }
      })
    },
    // 获取优惠券下拉
    async getCouponSelect({loanRecordId}) {
      const res = await fetchAvailableCoupons({loanRecordId})
      if (res.code === 1) {
        this.couponSelectList = res.data
        if (this.couponSelectList.length) {
          this.couponSelectList.unshift({
            name: this.$t('不使用券'),
            id: 10001
          })
          this.$set(this.form, 'couponId', 10001)
        } else {
          this.couponSelectList.unshift({
            name: this.$t('无可用券'),
            id: 10002
          })
          this.$set(this.form, 'couponId', 10002)
        }
      } else {
        this.couponSelectList.unshift({
          name: this.$t('无可用券'),
          id: 10002
        })
        this.$set(this.form, 'couponId', 10002)
      }
    },
    couponChange(id) {
      const value = this.couponSelectList.find(item => item.id === id)
      if (value && value.deductibleAmount) {
        const notRefundAmount = this.rows.notRefundAmount - value.deductibleAmount
        if (notRefundAmount >= 0) {
          this.$set(this.form, 'notRefundAmount', notRefundAmount.toFixed(0))
        } else {
          this.$set(this.form, 'notRefundAmount', 0)
        }
      } else {
        this.$set(this.form, 'notRefundAmount', this.rows.notRefundAmount)
      }
    },
    clearForm() {
      this.form = {}
      this.couponSelectList = []
      this.$refs.form.resetFields()
    }
  }
}
</script>

<style scoped>

</style>
